// popup.js - 修复通信问题
document.addEventListener('DOMContentLoaded', function () {
    const exportBtn = document.getElementById('exportBtn');
    const statusBtn = document.getElementById('statusBtn');
    const stopBtn = document.getElementById('stopBtn');
    const progressContainer = document.getElementById('progressContainer');
    const progressFill = document.getElementById('progressFill');
    const progressText = document.getElementById('progressText');
    const logContainer = document.getElementById('logContainer');
    const waybillCount = document.getElementById('waybillCount');
    const printableCount = document.getElementById('printableCount');
    const pageStatus = document.getElementById('pageStatus');
    const autoUncheckPacking = document.getElementById('autoUncheckPacking');
    const processDelay = document.getElementById('processDelay');
    const pdfNaming = document.getElementById('pdfNaming');

    let isProcessing = false;
    let currentTabId = null;

    // 初始化
    init();

    async function init() {
        addLog('正在初始化扩展...', 'info');

        try {
            // 获取当前标签页
            const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
            currentTabId = tab.id;
            addLog(`当前标签页: ${tab.url}`, 'info');

            // 检查页面兼容性
            const isCompatible = await checkPageCompatibility();

            if (isCompatible) {
                // 检查页面状态
                await checkPageStatus();
                // 加载设置
                loadSettings();
                // 监听消息
                chrome.runtime.onMessage.addListener(handleMessage);
            }

        } catch (error) {
            addLog('初始化失败: ' + error.message, 'error');
        }
    }

    // 新增：检查页面兼容性
    async function checkPageCompatibility() {
        try {
            const [tab] = await chrome.tabs.query({active: true, currentWindow: true});

            // 检查URL是否匹配Temu物流面单页面
            const isTemuWaybillPage = tab.url.includes('temu.com') &&
                tab.url.includes('/mmsos/waybill.html');

            if (!isTemuWaybillPage) {
                addLog('❌ 请在Temu物流面单页面使用此扩展', 'error');
                exportBtn.disabled = true;
                statusBtn.disabled = true;
                return false;
            }

            return true;
        } catch (error) {
            addLog('页面兼容性检查失败: ' + error.message, 'error');
            return false;
        }
    }

    async function checkPageStatus() {
        addLog('正在检查页面状态...', 'info');

        try {
            const response = await sendMessageWithRetry({
                action: 'getStatus'
            }, 3); // 重试3次

            if (response && response.success) {
                const status = response.data;
                updateStatusDisplay(status);
                addLog(`页面状态: ${status.totalWaybills}个运单，${status.printableCount}个可打印`, 'success');
            } else {
                throw new Error(response?.error || '无法获取页面状态');
            }
        } catch (error) {
            handleStatusError(error);
        }
    }

    // 新增：带重试的消息发送
    async function sendMessageWithRetry(message, maxRetries = 3) {
        for (let attempt = 1; attempt <= maxRetries; attempt++) {
            try {
                const response = await chrome.tabs.sendMessage(currentTabId, message);
                return response;
            } catch (error) {
                if (attempt === maxRetries) {
                    throw error;
                }
                addLog(`通信重试 ${attempt}/${maxRetries}...`, 'warning');
                await new Promise(resolve => setTimeout(resolve, 1000));
            }
        }
    }

    function updateStatusDisplay(status) {
        waybillCount.textContent = status.totalWaybills || 0;
        printableCount.textContent = status.printableCount || 0;

        if (status.isSupportedPage) {
            pageStatus.textContent = '支持';
            pageStatus.style.color = '#52c41a';
            exportBtn.disabled = status.totalWaybills === 0;
            statusBtn.disabled = false;
        } else {
            pageStatus.textContent = '不支持';
            pageStatus.style.color = '#ff4d4f';
            exportBtn.disabled = true;
            statusBtn.disabled = false;
        }

        if (status.error) {
            addLog('状态检查警告: ' + status.error, 'warning');
        }
    }

    function handleStatusError(error) {
        console.error('状态检查错误:', error);
        waybillCount.textContent = '-';
        printableCount.textContent = '-';
        pageStatus.textContent = '通信失败';
        pageStatus.style.color = '#ff4d4f';
        exportBtn.disabled = true;

        let errorMsg = '无法与页面通信: ' + error.message;
        if (error.message.includes('Could not establish connection')) {
            errorMsg += '\n可能的原因:\n- 页面未完全加载\n- 扩展权限问题\n- 请刷新页面后重试';
            addLog(errorMsg, 'error');
            addLog('💡 解决方案: 请刷新Temu页面，然后重新打开扩展', 'info');
        } else {
            addLog(errorMsg, 'error');
        }
    }

    function loadSettings() {
        chrome.storage.local.get(['autoUncheckPacking', 'processDelay', 'pdfNaming'], function (result) {
            autoUncheckPacking.checked = result.autoUncheckPacking !== false;
            processDelay.value = result.processDelay || 3;
            pdfNaming.value = result.pdfNaming || 'waybill';
            addLog('设置已加载', 'info');
        });
    }

    function saveSettings() {
        chrome.storage.local.set({
            autoUncheckPacking: autoUncheckPacking.checked,
            processDelay: parseInt(processDelay.value),
            pdfNaming: pdfNaming.value
        });
        addLog('设置已保存', 'info');
    }

    exportBtn.addEventListener('click', async function () {
        if (isProcessing) return;

        isProcessing = true;
        exportBtn.disabled = true;
        statusBtn.disabled = true;
        stopBtn.style.display = 'block';
        progressContainer.style.display = 'block';

        // 保存设置
        saveSettings();

        addLog('开始批量导出处理...', 'info');

        try {
            const settings = {
                autoUncheckPacking: autoUncheckPacking.checked,
                processDelay: parseInt(processDelay.value) * 1000,
                pdfNaming: pdfNaming.value
            };

            console.log('📤 发送导出请求，设置:', settings);

            const response = await sendMessageWithRetry({
                action: 'startExport',
                settings: settings
            });

            console.log('📥 收到响应:', response);

            if (response && response.success) {
                addLog('导出任务已启动', 'success');
            } else {
                throw new Error(response?.error || '启动失败');
            }
        } catch (error) {
            console.error('导出启动错误:', error);
            addLog('启动失败: ' + error.message, 'error');

            // 如果是连接错误，提供具体建议
            if (error.message.includes('Could not establish connection')) {
                addLog('💡 请确保:\n1. 在Temu物流面单页面\n2. 页面已完全加载\n3. 刷新页面后重试', 'info');
            }

            resetUI();
        }
    });

    statusBtn.addEventListener('click', function () {
        addLog('刷新页面状态...', 'info');
        checkPageStatus();
    });

    stopBtn.addEventListener('click', async function () {
        try {
            await sendMessageWithRetry({action: 'stopExport'});
            addLog('已发送停止信号', 'info');
        } catch (error) {
            addLog('停止失败: ' + error.message, 'error');
        }
        resetUI();
    });

    function handleMessage(request, sender, sendResponse) {
        console.log('popup收到消息:', request);

        switch (request.action) {
            case 'progressUpdate':
                updateProgress(request.data);
                break;

            case 'exportComplete':
                handleExportComplete(request.data);
                break;

            case 'exportError':
                handleExportError(request.data);
                break;

            case 'exportStopped':
                handleExportStopped(request.data);
                break;

            case 'contentScriptReady':
                addLog('✅ 页面脚本已就绪', 'success');
                checkPageStatus();
                break;

            case 'debugInfo':
                console.log('调试信息:', request.data);
                break;
        }
    }

    function updateProgress(progress) {
        const percentage = Math.round((progress.current / progress.total) * 100);
        progressFill.style.width = percentage + '%';
        progressText.textContent = `处理中: ${progress.current}/${progress.total} (${percentage}%)`;

        if (progress.message) {
            addLog(progress.message, progress.type || 'info');
        }

        // 检查是否完成
        if (progress.current === progress.total && progress.type !== 'error') {
            progressText.textContent = '处理完成!';
            progressFill.style.backgroundColor = '#52c41a';
        }
    }

    function handleExportComplete(data) {
        addLog(`✅ 批量处理完成!`, 'success');
        addLog(`总运单: ${data.total} | 成功: ${data.success} | 失败: ${data.failed}`, 'success');

        if (data.fileName) {
            addLog(`Excel文件已生成: ${data.fileName}`, 'success');
        }
        if (data.zipName) {
            addLog(`PDF压缩包已生成: ${data.zipName}`, 'success');
        }

        progressText.textContent = '处理完成!';
        progressFill.style.backgroundColor = '#52c41a';

        setTimeout(() => {
            resetUI();
            checkPageStatus();
        }, 3000);
    }

    function handleExportError(data) {
        addLog('❌ 导出失败: ' + data.error, 'error');
        progressFill.style.backgroundColor = '#ff4d4f';
        resetUI();
    }

    function handleExportStopped(data) {
        addLog(`⏹️ 处理已停止 (已处理 ${data.processed}/${data.total})`, 'info');
        resetUI();
    }

    function resetUI() {
        isProcessing = false;
        exportBtn.disabled = false;
        statusBtn.disabled = false;
        stopBtn.style.display = 'none';
        progressContainer.style.display = 'none';
        progressFill.style.width = '0%';
        progressFill.style.backgroundColor = '#1890ff';
        progressText.textContent = '准备开始...';
    }

    function addLog(message, type = 'info') {
        const logEntry = document.createElement('div');
        logEntry.className = `log-entry log-${type}`;

        const timestamp = new Date().toLocaleTimeString();
        logEntry.textContent = `[${timestamp}] ${message}`;

        logContainer.appendChild(logEntry);
        logContainer.scrollTop = logContainer.scrollHeight;

        // 限制日志数量
        const logs = logContainer.getElementsByClassName('log-entry');
        if (logs.length > 50) {
            logs[0].remove();
        }
    }

    // 设置变化时自动保存
    autoUncheckPacking.addEventListener('change', saveSettings);
    processDelay.addEventListener('change', saveSettings);
    pdfNaming.addEventListener('change', saveSettings);

    // 添加调试信息
    addLog('扩展初始化完成', 'info');
    addLog('点击"刷新状态"检查页面兼容性', 'info');
});

// 添加错误处理
window.addEventListener('error', function (e) {
    console.error('Popup错误:', e.error);
});
